//
//  ImageViewerController.m
//  Zyachting
//
//  Created by NGUYEN THE HUNG on 10/18/12.
//
//

#import "ImageViewerController.h"
#import "UIImageView+WebCache.h"

#define kIMAGE_WIDTH 320
#define kIMAGE_HEIGHT 214
#define kCOVER_HEIGHT 250
@interface ImageViewerController ()

@end
BOOL pageControlIsChangingPage;
@implementation ImageViewerController
@synthesize imageList,scrollView,pageControl,isLocal;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupScrollView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)setupScrollView
{
    [self.scrollView setContentSize:CGSizeMake(kIMAGE_WIDTH * self.imageList.count, kIMAGE_HEIGHT)];
    [self.scrollView setPagingEnabled:YES];
    [self.pageControl setNumberOfPages:self.imageList.count];
    [self.pageControl setCurrentPage:0];
    for (int i = 0; i< self.imageList.count; i++) {
        UIImageView* iv = [[UIImageView alloc] initWithFrame:CGRectMake(kIMAGE_WIDTH*i, 0, kIMAGE_WIDTH, kIMAGE_HEIGHT)];

        [self.scrollView addSubview:iv];
        if (self.isLocal) {
            [iv setImage:[UIImage imageNamed:[self.imageList objectAtIndex:i]]];
        }else{
            NSString* urlString = [self.imageList objectAtIndex:i][@"imgpath"];
            NSLog(urlString);
            [iv setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        }

        [iv  release];
        
    }
}

#pragma mark -Action
-(IBAction)pageControlChanged:(id)sender
{
    /*
	 *	Change the scroll view
	 */
    CGRect frame = self.scrollView.frame;
    frame.origin.x = frame.size.width * pageControl.currentPage;
    frame.origin.y = 0;
	
    [self.scrollView scrollRectToVisible:frame animated:YES];
    
	/*
	 *	When the animated scrolling finishings, scrollViewDidEndDecelerating will turn this off
	 */
    pageControlIsChangingPage = YES;
}
#pragma mark -Scrollview Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (pageControlIsChangingPage) {
        return;
    }
    
	/*
	 *	We switch page at 50% across
	 */
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)_scrollView
{
    pageControlIsChangingPage = NO;
}
@end
